<template>
  <div>
    <!--    面包屑导航-->
    <el-breadcrumb separator="》">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    视图区-->
    <el-card>
      <!--      搜索栏-->
      <el-row :gutter="30">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.query"
                    clearable @clear="searchUser">
            <el-button slot="append" icon="el-icon-search"
                       @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--      表格区-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
                       @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
                       @click="showEditDialog(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini"
            ></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top"
                        :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页-->
      <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pagenum"
              :page-sizes="[2, 3, 5 ,10,20]"
              :page-size="queryInfo.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
      </el-pagination>
    </el-card>
    <!--    添加用户的对话框-->
    <el-dialog
            title="添加用户"
            :visible.sync="addDialogVisible"
            width="60%"
            @close="closeDialog">
      <!--      添加信息-->
      <el-form :model="addForm" :rules="addFormRules" label-width="80px"
               ref="addFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" type="email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile" type="phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>
    <!--    修改用户的对话框-->
    <el-dialog
            title="修改用户"
            :visible.sync="editDialogVisible"
            width="60%"
            @close="editDialogClosed">
      <!--      修改信息-->
      <el-form :model="editForm" :rules="addFormRules" label-width="80px"
               ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" type="email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile" type="phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Users",
    data() {
      // 自定义邮箱规则
      const checkEmail = (rule, value, callback) => {
        const regEmail = /^\w+@\w+(\.\w+)+$/
        if (regEmail.test(value)) {
          // 合法邮箱
          return callback()
        }
        callback(new Error('请输入合法邮箱'))
      };
      // 自定义手机号规则
      const checkMobile = (rule, value, callback) => {
        const regMobile = /^1[34578]\d{9}$/
        if (regMobile.test(value)) {
          return callback()
        }
        // 返回一个错误提示
        callback(new Error('请输入合法的手机号码'))
      };
      return {
        // 请求对象，请求页和每页数量
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 5
        },
        userList: [],
        total: 0,
        // 添加用户部分
        addDialogVisible: false,
        editDialogVisible: false,
        // 数据对象
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 验证规则
        addFormRules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'}
          ],
          // email: [
          //   {required: true, message: '请输入邮箱', trigger: 'blur'},
          //   {validator: checkEmail, trigger: 'blur'}
          // ],
          // mobile: [
          //   {required: true, message: '请输入手机号码', trigger: 'blur'},
          //   {validator: checkMobile, trigger: 'blur'}
          // ]
        },
        editForm:{
          id:'',
          username:'',
          email:'',
          mobile:''
        }
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      async getUserList() {
        const {data: res} = await this.$http.get('users', {params: this.queryInfo})
        if (res.meta.status !== 200) this.$message.error('获取用户列表失败')
        else {
          this.userList = res.data.users
          this.total = res.data.total
          console.log(this.userList)
        }
      },
      searchUser() {
        this.handleCurrentChange(1)
      },
      handleSizeChange(newPageSize) {
        this.queryInfo.pagesize = newPageSize
        this.getUserList()
      },
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      async userStateChanged(userInfo) {
        const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${
            userInfo.mg_state}`)
        // console.log(res)
        if (res.meta.status !== 200) {
          res.mg_state = !res.mg_state
          return this.$message.error('修改失败')
        } else
          return this.$message.success('修改成功')
      },
      closeDialog() {
        this.$refs.addFormRef.resetFields()
      },
      addUser() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          const {data: res} = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败')
            // console.log(res)
          } else {
            this.$message.success('添加用户成功')
            this.addDialogVisible = false
            await this.getUserList()
          }
        })
      },
      showEditDialog(value) {
        this.editDialogVisible = true
        this.editForm.id=value.id
        this.editForm.username=value.username
        this.editForm.email=value.email
        this.editForm.mobile=value.mobile
        // console.log(value)
      },
      // 监听修改用户对话框的关闭事件,如果有信息为空,读取时老的信息不会被覆盖
      editDialogClosed () {
        this.$refs.editFormRef.resetFields()
      },
      // 修改用户信息
      editUser () {
        // 提交请求前，表单预验证
        this.$refs.editFormRef.validate(async valid => {
          // console.log(valid)
          // 表单预校验失败
          if (!valid) return
          const { data: res } = await this.$http.put(
              'users/' + this.editForm.id,
              {
                email: this.editForm.email,
                mobile: this.editForm.mobile
              }
          )
          if (res.meta.status !== 200) {
            this.$message.error('更新用户信息失败！')
          }
          // 隐藏添加用户对话框
          this.editDialogVisible = false
          this.$message.success('更新用户信息成功！')
          await this.getUserList()
        })
      },
    }
  }
</script>

<style lang="less" scoped>
  .el-table {
    margin-top: 25px;
    font-size: 14px;
  }
</style>
